<?php

namespace MicroCyan\ThinkHelp\Kernel;

use think\facade\Validate;

class DataSetting
{

    protected $perhaps  = [];
    protected $defaults = [];
    protected $rule = [];
    protected $message=[];

    /**
     * @var Validate
     */
    public $validate = null;

    public function __construct(){
        $this->defaults= array_map(function ($v){ return $v==='now'?time():$v; },$this->defaults??[]);
        $this->validate = Validate::rule($this->rule)->message($this->message);
    }
    /**
     * @param $keys
     * @return array
     */
    public function build_by_input($keys): array
    {
        $data = input();
        return $this->build($data,$keys);
    }

    public function turnBoolean($data,$fields): array
    {
        if (is_string($fields)) $fields = explode(',',$fields);
        if (!is_array($fields)) return $data;
        foreach ($fields as $field){
            if (isEmptyStr($field))continue;
            $data[$field] = !empty($data[$field]);
        }
        return $data;
    }
    public function turnJson($data,$fields): array
    {
        if (is_string($fields)) $fields = explode(',',$fields);
        if (!is_array($fields)) return $data;
        foreach ($fields as $field){
            if (isEmptyStr($field))continue;
            $data[$field] = json_encode($data[$field]??'',JSON_UNESCAPED_UNICODE);
        }
        return $data;
    }
    /**
     * @param $data
     * @param $keys
     * @return array
     */
    public function build($data,$keys): array
    {
        //如果为数组数据，要进行格式化
        $data = array_map(function ($iv){ return is_array($iv)?json_encode($iv,JSON_UNESCAPED_UNICODE):$iv; },$data);
        //如果key以字符串的形式，则进行分割
        if (is_string($keys)) { $keys = explode(',', $keys); };
        $e = [];
        //如果是有效的keys，则进行遍历
        if (is_array($keys) && !empty($keys)){
            foreach ($keys as $key){
                $e[$key] = trim($this->defaults[$key]??'');
                if (empty($this->perhaps[$key])){ $this->perhaps[$key] = []; }
                $this->perhaps[$key][] = $key;
                foreach ($this->perhaps[$key] as $v){
                    //如果在可能的键值中可以找到对应值，则直接赋值覆盖掉默认值
                    if (isset($data[$v])){ $e[$key] = trim($data[$v]); break; }
                }
            }
        }
        return $e;
    }

}